package com.xmzs.common.chat.config;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.xmzs.common.chat.entity.chat.Message;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.ListIterator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 *
 * @author https:www.unfbx.com
 * @date 2023-03-10
 */
@Slf4j
public class LocalCache {
    /**
     * 缓存时长
     */
    public static final long TIMEOUT = 30 * DateUnit.MINUTE.getMillis();
    /**
     * 清理间隔
     */
    private static final long CLEAN_TIMEOUT = 30 * DateUnit.MINUTE.getMillis();

    /**
     * 缓存对象
     */
    public static final TimedCache<String, Object> CACHE = CacheUtil.newTimedCache(TIMEOUT);

    public static Cache<String, LinkedList<Message>> MESSAGE;

    static {
        // 初始化 共用的 缓存
        MESSAGE  = CacheBuilder.newBuilder().initialCapacity(100000).expireAfterAccess(720, TimeUnit.MINUTES).build();
    }

    static {
        //启动定时任务
        CACHE.schedulePrune(CLEAN_TIMEOUT);
    }

    /**
     * 获取缓存
     * @param key 缓存key
     * @param contentNumber 获取记录条数
     * @return LinkedList<Message>
     */
    public static LinkedList<Message> getUserChatMessages(String key,Integer contentNumber){
        LinkedList<Message> contextInfo = new LinkedList<>();
        try {
            contextInfo = MESSAGE.get(key, LinkedList::new);
            // 删除列表中的第一条数据
            contextInfo.pollFirst();
        } catch (ExecutionException e) {
            log.error("获取缓存失败{},参数：{}",e.getMessage(),key);
        }
        // 添加元素到contextInfo中
        LinkedList<Message> lastSixElements = new LinkedList<>();
        int userContextInfoSize = contextInfo.size();
        int startIndex = userContextInfoSize - contentNumber;
        if (startIndex >= 0) {
            ListIterator<Message> iterator = contextInfo.listIterator(startIndex);
            while (iterator.hasNext()) {
                lastSixElements.addFirst(iterator.next());
            }
        } else {
            lastSixElements.addAll(contextInfo);
        }
        return lastSixElements;
    }
}
